/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 * http://dangerousprototypes.com/docs/Bitbang#00001111_-_Reset_Bus_Pirate
 */
package cnc;

import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;
import jssc.SerialPort;
import jssc.SerialPortException;
import jssc.SerialPortEvent;
import jssc.SerialPortEventListener;

class move{
    boolean dir;
    boolean move;
    
    move(boolean tdir, boolean tmove){
        dir = tdir;
        move = tmove;
    }
    
}
/**
 *
 * @author PiotrGl
 */
public class CncDevice {

    private static SerialPort serialPort;

    public CncDevice() {
    }

    public int Connect(String PortName) {
        serialPort = new SerialPort(PortName);
        try {
            serialPort.openPort();//Open serial port
            serialPort.setParams(SerialPort.BAUDRATE_115200,
                    SerialPort.DATABITS_8,
                    SerialPort.STOPBITS_1,
                    SerialPort.PARITY_NONE,
                    false,
                    false);//Set params. Also you can set params by this string: serialPort.setParams(9600, 8, 1, 0);

            serialPort.addEventListener(new SerialPortReader());
            
            //serialPort.writeInt(0x00);

            //serialPort.writeInt('i');
            //@SuppressWarnings("MismatchedReadAndWriteOfArray")
            //byte buffer[] = serialPort.readBytes(10);                  
            //System.out.println(buffer);
            //serialPort.writeBytes("This is a test string".getBytes());//Write data to port
            //this.serialPort = serialPort;
            //serialPort.closePort();//Close serial port
        } catch (SerialPortException ex) {
            System.out.println(ex);
            serialPort = null;
            return -1;
        }

        return 0;
    }

    public int Disconnect() {
        try {
            serialPort.closePort();
            serialPort = null;
        } catch (SerialPortException ex) {
            System.out.println(ex);
            return -1;
        }

        return 0;
    }

    public SerialPort getPort() {
        return serialPort;
    }
    
    static class SerialPortReader implements SerialPortEventListener {

        @Override
        public void serialEvent(SerialPortEvent event) {
            if (event.isRXCHAR()) {//If data is available
                // if(event.getEventValue() == 1){//Check bytes count in the input buffer
                //Read data, if 10 bytes available 
                try {
                    if (event.isRXCHAR()) {
                        @SuppressWarnings("MismatchedReadAndWriteOfArray")
                        byte buffer[] = serialPort.readBytes();
                        String value = new String(buffer, "UTF-8");
                        System.out.println(value);
                        //odebrana wiadomosc w value
                        
                    }
                } catch (SerialPortException ex) {
                    System.out.println(ex);
                } catch (UnsupportedEncodingException ex) {
                    System.out.println(ex);
                }
                //  }
            } else if (event.isCTS()) {//If CTS line has changed state
                if (event.getEventValue() == 1) {//If line is ON
                    System.out.println("CTS - ON");
                } else {
                    System.out.println("CTS - OFF");
                }
            } else if (event.isDSR()) {///If DSR line has changed state
                if (event.getEventValue() == 1) {//If line is ON
                    System.out.println("DSR - ON");
                } else {
                    System.out.println("DSR - OFF");
                }
            }
        }
    }
    
    
    /**
     *
     * @param x
     * @param y
     * @param z
     * send 0b1 xdir xmove ydir ymove zdir zmove Lon
     */
    public void move(move x, move y, move z){
        int command = 0x80;
        if (x.dir) command += 0x40;
        if (x.move) command += 0x20;
        
        if (y.dir) command += 0x10;
        if (y.move) command += 0x08;
        
        if (z.dir) command += 0x04;
        if (z.move) command += 0x02;
        
        System.out.println(Integer.toString(command, 16));//String.valueOf(command));
        
        try {            
            serialPort.writeInt(command);
        } catch (SerialPortException ex) {
            System.out.println("blad wyslania komendy ruchu " + ex);
        } catch (NullPointerException e){
            System.out.println("brak otwaretego portu " + e);
        }
    }
    /*
     * 0b1 on
     * 0b0 off
     * 0b10 def curent
     * 0b11 set curent val
     * 0b100 normal
     * 0b101 half
     * 0b110 normal+half
     */    
    public static int command_on = 1;
    public static int command_off = 0;
    public static int command_def_curent =2;
    public static int command_set_curent =3;
    
    /*
     * send 0b0 x,y,z,a command 0bvalue_hight 0bvalue_low
     */
    public void command(int device, int command, int value){
        
        device = device%16;
        command = command%8;
        if (command!=3) {
            System.out.println("device: " + Integer.toString((device), 2) +  " command:" + Integer.toString((command), 2));//String.valueOf(command));
            try {
                serialPort.writeInt(device*8+command);
            } catch (SerialPortException ex) {
                System.out.println("blad wyslania komendy 1 " + ex);
            } catch (NullPointerException e){
                System.out.println("brak otwaretego portu " + e);
            }
        } else {
            System.out.println("device: " + Integer.toString((device), 2) +  " command:" + Integer.toString((command), 2)+" "+Integer.toString(value/256, 16)+" "+Integer.toString(value%256, 16));
        }
//        try {            
//            serialPort.writeInt(device*8+command);
//        } catch (SerialPortException ex) {
//            System.out.println(ex);
//        } 
    }
    
    
}


